package com.ruicar.afs.cloud.product.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.product.condition.ExtrasProgramCondition;
import com.ruicar.afs.cloud.product.condition.ExtrasProgramConfigCondition;
import com.ruicar.afs.cloud.product.entity.ExtrasInfo;
import com.ruicar.afs.cloud.product.entity.ExtrasProgramInfo;
import com.ruicar.afs.cloud.product.entity.ExtrasProjectProgramInfo;
import com.ruicar.afs.cloud.product.entity.ProductPlan;
import com.ruicar.afs.cloud.product.enums.StatusEnum;
import com.ruicar.afs.cloud.product.service.ExtrasProgramConfigService;
import com.ruicar.afs.cloud.product.service.ExtrasProgramService;
import com.ruicar.afs.cloud.product.service.ExtrasProjectService;
import com.ruicar.afs.cloud.product.service.ProductPlanService;
import com.ruicar.afs.cloud.product.vo.ExtrasInfoVo;
import com.ruicar.afs.cloud.product.vo.ExtrasProgramInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author xudongdong
 * @date 2020-05-14
 */
@RestController
@AllArgsConstructor
@RequestMapping("/extrasProgramConfig")
@Api(value = "extrasProgramConfig", description = "附加贷方案配置信息")
public class ExtrasProgramConfigController {

    private final ProductPlanService productPlanService;
    private final ExtrasProjectService extrasService;
    private final ExtrasProgramService extrasProgramService;
    private final ExtrasProgramConfigService extrasProgramConfigService;

    @PostMapping("/getExtrasProjectDatas")
    @ApiOperation(value = "分页获取附加贷方案数据")
    public IResponse<IPage<ExtrasProgramInfoVo>> getExtrasProjectDatas(@RequestBody ExtrasProgramConfigCondition extrasProgramConfig) {

        Page page = new Page(extrasProgramConfig.getPageNumber(), extrasProgramConfig.getPageSize());
        IPage<List<ExtrasProgramInfoVo>> list = extrasProgramConfigService.getExtrasConfigProgramList(page, extrasProgramConfig);
        return IResponse.success(list);
    }

    @PostMapping(value = "/saveExtrasProject")
    @ApiOperation(value = "保存附加贷项目")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<Boolean> saveExtrasProject(@ModelAttribute ExtrasProgramConfigCondition extrasProgramConfig) {
        //根据附加贷ID查询，附加方案项目中排序最大的一条数据
        ExtrasProjectProgramInfo projectAndPlan = extrasProgramConfigService.getOne(Wrappers.<ExtrasProjectProgramInfo>query().lambda()
                .eq(ExtrasProjectProgramInfo::getExtrasPlanId, extrasProgramConfig.getExtrasPlanId()).orderByDesc(ExtrasProjectProgramInfo::getSerialNumber), false);
        //附加项目存在数据则最大排序加1，否则默认排序为1
        int serialNumber = 0;
        if (projectAndPlan != null) {
            serialNumber = projectAndPlan.getSerialNumber() + 1;
        }
        //根据前端勾选项查询相关附加项目列表
        List<ExtrasInfo> extrasInfoList = extrasService.listByIds(Arrays.asList(extrasProgramConfig.getIds()));
        //查询勾选项的父集编号，并将列表合并
        List<String> idList = new ArrayList<String>();
        extrasInfoList.forEach(extrasInfo -> {
            if (AfsEnumUtil.key(StatusEnum.YES).equals(extrasInfo.getIsExistsFather())) {
                idList.add(extrasInfo.getFatherNo());
            }
        });
        //合并父集列表
        if (idList.size() > 0) {
            idList.forEach(fatherNo -> {
                //查询父集
                List<ExtrasInfo> fatherList = extrasService.list(Wrappers.<ExtrasInfo>query().lambda()
                        .eq(ExtrasInfo::getExtrasProjectNo, fatherNo)
                );
                //合并父集
                extrasInfoList.addAll(fatherList);
            });
        }
        //查询已经保存的附加项目列表
        List<ExtrasInfo> listSave = new ArrayList<>();
        List<ExtrasProjectProgramInfo> list = extrasProgramConfigService.list(Wrappers.<ExtrasProjectProgramInfo>query().lambda()
                .eq(ExtrasProjectProgramInfo::getExtrasPlanId, extrasProgramConfig.getExtrasPlanId()));
        //勾选的附加项目列表去除已经保存的项目
        list.forEach(projectProgramInfo -> {
            extrasInfoList.forEach(extrasInfo -> {
                if (extrasInfo.getId().equals(projectProgramInfo.getExtrasProjectId())) {
                    listSave.add(extrasInfo);
                }
            });
        });
        extrasInfoList.removeAll(listSave);//去除保存的附加项

        //去除重复数据
        Set<ExtrasInfo> resultlist = new HashSet<ExtrasInfo>();
        resultlist.addAll(extrasInfoList);
        String extrasProjectName = "";
        //保存附加项目以及其父集项目
        for (ExtrasInfo extrasInfo : resultlist) {
            ExtrasProjectProgramInfo projectplan = new ExtrasProjectProgramInfo(extrasProgramConfig.getExtrasPlanId(), extrasInfo.getId(), serialNumber);
            serialNumber++;
            extrasProgramConfigService.save(projectplan);
            extrasProjectName += extrasInfo.getExtrasProjectName() + ",";
        }
        extrasProjectName = extrasProjectName.substring(0, extrasProjectName.length() - 1);
        ExtrasProgramInfo extrasProgramInfo = extrasProgramService.getById(extrasProgramConfig.getExtrasPlanId());
        if (StringUtils.isNotEmpty(extrasProgramInfo.getExtrasProjectName())) {
            extrasProgramInfo.setExtrasProjectName(extrasProgramInfo.getExtrasProjectName() + "," + extrasProjectName);
        } else {
            extrasProgramInfo.setExtrasProjectName(extrasProjectName);
        }
        extrasProgramService.updateById(extrasProgramInfo);

        return IResponse.success("操作成功");
    }

    @PostMapping("/upPlan")
    @ApiOperation(value = "上移项目")
    @SysLog("上移项目")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<Boolean> upPlan(@ModelAttribute ExtrasProgramConfigCondition extrasProgramConfig) {
        ExtrasProjectProgramInfo projectAndPlan = extrasProgramConfigService.getById(extrasProgramConfig.getId());
        Boolean flag = extrasProgramConfigService.update(Wrappers.<ExtrasProjectProgramInfo>update().lambda().set(ExtrasProjectProgramInfo::getSerialNumber, projectAndPlan.getSerialNumber())
                .eq(ExtrasProjectProgramInfo::getSerialNumber, projectAndPlan.getSerialNumber() - 1)
                .eq(ExtrasProjectProgramInfo::getExtrasPlanId, projectAndPlan.getExtrasPlanId())
        );
        if (!flag) {
            return IResponse.fail("不可上移");
        }
        projectAndPlan.setSerialNumber(projectAndPlan.getSerialNumber() - 1);
        extrasProgramConfigService.updateById(projectAndPlan);
        return new IResponse<Boolean>().setData(true).setMsg("上移项目成功");
    }

    @PostMapping("/downPlan")
    @ApiOperation(value = "下移项目")
    @SysLog("下移项目")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<Boolean> downPlan(@ModelAttribute ExtrasProgramConfigCondition extrasProgramConfig) {
        ExtrasProjectProgramInfo projectAndPlan = extrasProgramConfigService.getById(extrasProgramConfig.getId());
        Boolean flag = extrasProgramConfigService.update(Wrappers.<ExtrasProjectProgramInfo>update().lambda().set(ExtrasProjectProgramInfo::getSerialNumber, projectAndPlan.getSerialNumber())
                .eq(ExtrasProjectProgramInfo::getSerialNumber, projectAndPlan.getSerialNumber() + 1)
                .eq(ExtrasProjectProgramInfo::getExtrasPlanId, projectAndPlan.getExtrasPlanId())
        );
        if (!flag) {
            return IResponse.fail("不可下移");
        }
        projectAndPlan.setSerialNumber(projectAndPlan.getSerialNumber() + 1);
        extrasProgramConfigService.updateById(projectAndPlan);
        return new IResponse<Boolean>().setData(true).setMsg("下移项目成功");
    }

    @RequestMapping(value = "/delById/{id}", method = RequestMethod.DELETE)
    @ApiOperation(value = "通过id删除")
    @Transactional
    @SysLog("删除附加贷项目信息")
    public IResponse<Boolean> delById(@PathVariable String id) {
        ExtrasProjectProgramInfo projectAndPlan = extrasProgramConfigService.getById(id);
        ExtrasInfo extrasInfo = extrasService.getById(projectAndPlan.getExtrasProjectId());
        ExtrasProgramInfo extrasProgramInfo = extrasProgramService.getById(projectAndPlan.getExtrasPlanId());
        if (AfsEnumUtil.key(StatusEnum.NO).equals(extrasInfo.getIsExistsFather())) {
            List<ExtrasProjectProgramInfo> list = extrasProgramConfigService.list(Wrappers.<ExtrasProjectProgramInfo>query().lambda()
                    .eq(ExtrasProjectProgramInfo::getExtrasPlanId, projectAndPlan.getExtrasPlanId()));
            for (ExtrasProjectProgramInfo projectProgramInfo : list) {
                ExtrasInfo extras = extrasService.getById(projectProgramInfo.getExtrasProjectId());
                if (extrasInfo.getExtrasProjectNo().equals(extras.getFatherNo())) {
                    return IResponse.fail("不可删除，请先删除子级！");
                }
            }
        }
        String[] oldExtrasProjectName = extrasProgramInfo.getExtrasProjectName().split(",");
        String newExtrasProjectName = "";
        if (oldExtrasProjectName.length > 1) {
            for (String s : oldExtrasProjectName) {
                if (!extrasInfo.getExtrasProjectName().equals(s)) {
                    newExtrasProjectName += s + ",";
                }
            }
            newExtrasProjectName = newExtrasProjectName.substring(0, newExtrasProjectName.length() - 1);
        }
        extrasProgramInfo.setExtrasProjectName(newExtrasProjectName);
        extrasProgramService.updateById(extrasProgramInfo);

        extrasProgramConfigService.removeById(id);
        extrasProgramConfigService.sequenceOrderById(extrasProgramInfo.getId().toString());

        return new IResponse<Boolean>().setMsg("删除数据成功");
    }

    @PostMapping("/getselectProductData")
    @ApiOperation(value = "获取产品信息")
    public IResponse<IPage<ExtrasInfoVo>> getselectProductData(@RequestBody ExtrasProgramCondition extrasProgramConfig) {
        Page page = new Page(extrasProgramConfig.getPageNumber(), extrasProgramConfig.getPageSize());
        IPage<List<ExtrasInfoVo>> list = extrasProgramConfigService.getselectProductData(page,extrasProgramConfig);
        return IResponse.success(list);
    }

    @PostMapping("/getselectProductDataByID")
    @ApiOperation(value = "根据产品ID获取产品信息")
    public IResponse<IPage<ExtrasInfoVo>> getselectProductDataByID(@RequestBody ExtrasProgramCondition extrasProgramConfig) {
        ProductPlan plan = productPlanService.getById(extrasProgramConfig.getProductPlanId());
        return IResponse.success(plan);
    }

    @RequestMapping(value = "/moveTemplateAll", method = RequestMethod.POST)
    @ApiOperation(value = "移动选中项目")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<Boolean> moveTemplateAll(@ModelAttribute ExtrasProgramConfigCondition extrasProgramConfig) {
        extrasProgramConfigService.moveTemplateAll(extrasProgramConfig);
        return IResponse.success("选中项目移动成功");
    }


}
